package com.cqhfan.imservice.handler;

import com.cqhfan.core.constans.BizConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author 眭传洪
 * @create 2025-08-16 1:54
 */
@Slf4j
@Component
public class ImConnectionHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 获取连接用户
        Long userId = getUserByWebSession(session);
        // 添加连接关系
        UserConnectionSession.addConnectionRelation(userId, session);
        log.info("userId = {}成功连接到websocket", userId);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 获取连接用户
        Long userId = getUserByWebSession(session);
        // 移除连接关系
        UserConnectionSession.removeConnectionRelation(userId);
        log.info("userId = {}成功断开websocket连接", userId);
    }

    private Long getUserByWebSession(WebSocketSession session) throws Exception {
        Object connectionAttribute = session.getAttributes().get(BizConstants.WEBSOCKET_CONNECTION_USER);
        if (connectionAttribute == null) {
            log.info("错误连接，sessionId = {}", session.getId());
            session.close(CloseStatus.BAD_DATA);
            return null;
        }
        return Long.valueOf(connectionAttribute.toString());
    }

}
